package xyz.xpman.prisonerfitness.config;

import android.annotation.SuppressLint;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class QQConfig {
    public static final QQConfig EMPTY = new QQConfig();
    private final String id;
    private final List<QQGroupConfig> group;

    @SuppressLint("NewApi")
    public QQConfig() {
        this.id = null;
        this.group = new ArrayList<>();
    }

    @SuppressLint("NewApi")
    public QQConfig(@NotNull List<QQGroupConfig> group) {
        this(null, group);
    }

    @SuppressLint("NewApi")
    public QQConfig(String id, @NotNull List<QQGroupConfig> group) {
        this.id = id;
        group.removeIf(item -> !item.getIsAvailable());
        this.group = group;
    }


    public String getId() {
        return id;
    }

    public boolean hasUsefulConfig() {
        return !group.isEmpty();
    }

    public QQGroupConfig getAvailableGroup() {
        return group.isEmpty() ? null : group.get(0);
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    public static QQConfig byJson(@NotNull JSONObject config) {
        try {
            JSONArray groupConfig = config.getJSONArray("group");
            final List<QQGroupConfig> items = new ArrayList<>();

            for(int i = 0; i < groupConfig.length(); i++){
                QQGroupConfig temp = QQGroupConfig.byJson(groupConfig.getJSONObject(i));

                if (null == temp) {
                    return EMPTY;
                }
                items.add(temp);
            }

            return new QQConfig(items);
        } catch (Exception e){
            e.printStackTrace();
        }
        return EMPTY;
    }


}

